<template>
  <div class="arrival-detail">
    <!-- 标题与返回 -->
    <div class="detail-header">
      <h2>到货详情（SHD001）</h2>
    </div>

    <!-- 基础信息 -->
    <el-form label-width="80px" class="info-form">
      <el-form-item label="到货日期">
        <el-input v-model="arrivalNote.arrivalDate" disabled/>
      </el-form-item>
      <el-form-item label="供应商">
        <el-input v-model="arrivalNote.supplierName" disabled/>
      </el-form-item>
      <el-form-item label="卸货库区">
        <el-input v-model="arrivalNote.storeAreaId" disabled/>
      </el-form-item>
    </el-form>

    <!-- 到货原料表格 -->
    <div class="material-section">
      <label class="section-title">到货原料：</label>
      <el-table :data="arrivalDetails" border stripe style="width: 100%">
        <el-table-column type="selection" align="center" width="50" />
        <el-table-column label="序号" align="center" width="60">
          <template #default="scope">
            {{ scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column prop="mcode" label="原料编码" align="center" />
        <el-table-column prop="name" label="原料名称" align="center" />
        <el-table-column prop="warmarea" label="存放温区" align="center" />
        <el-table-column prop="spec" label="原料规格" align="center" />
        <el-table-column label="采购数量">
          <template v-slot="{ row }">
            {{ row.num }} {{ row.unit || '' }}
          </template>
        </el-table-column>
        <el-table-column label="到货数量" width="270">
        <template v-slot="{ row }">

          {{ row.arrivalNum }} {{ row.unit || '' }}

        </template>
      </el-table-column>
        <el-table-column prop="note" label="备注" align="center" />
      </el-table>
    </div>

    <!-- 备注 -->
    <div class="remark-section">
      <label class="section-title">备注：</label>
      <el-input type="textarea" v-model="arrivalNote.note" disabled rows="3" placeholder="请输入备注信息" />
    </div>

    <!-- 操作按钮 -->
    <div class="action-buttons">
      <el-button type="primary" @click="handleEdit">编辑</el-button>
      <el-button type="primary" @click="handlePrintBarcode">打印原料条码</el-button>
      <el-button type="primary" @click="handlePrintOrder">打印到货单</el-button>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { getArrivalDetailById } from '@/api/arrival/arrival.js'
import { ElMessage } from 'element-plus'

const route = useRoute()
const router = useRouter()

// 响应式数据（主数据+明细数据）
const arrivalNote = ref({
  arrivalDate: '',
  supplierName: '',
  storeAreaId: '',
  note: '',
  arrivalMaterialDetailList: [] // 初始化明细数组
})
const arrivalDetails = ref([]) // 专门存明细，给表格用

// 根据ID查询详情
async function init(id){
  try {
    let res = await getArrivalDetailById({ id });
    if(res.code === 200){
      // 1. 从data数组取第1个元素（到货单对象）
      const arrivalObj = res.data[0] || {};
      arrivalNote.value = arrivalObj;

      // 2. 提取明细数组，赋值给表格数据源
      const detailList = arrivalObj.arrivalMaterialDetailList || [];
      console.log("到货原料明细数据：", detailList); 
      arrivalDetails.value = detailList;

      // 3. 无明细提示
      if (detailList.length === 0) {
        ElMessage({ type: 'info', message: '当前到货单无原料明细' });
      }
    } else {
      ElMessage({ type: 'error', message: `获取详情失败：${res.msg}` });
    }
  } catch (error) {
    ElMessage({ type: 'error', message: `请求异常：${error.message}` });
  }
}

// 页面挂载时获取ID并查数据
onMounted(()=>{
  const id = route.query.id;
  if (!id) {
    ElMessage.warning('未获取到到货单ID');
    router.push('/arrival/record'); // 跳回列表页
    return;
  }
  init(id);
})

// 编辑按钮（修复ID获取方式）
const handleEdit = () => {
  const id = route.query.id;
  if (!id) {
    ElMessage.warning('无法编辑，缺少到货单详情ID');
    return;
  }
  router.push(`/arrival/edit?id=${id}`); // 用query传ID
}

// 打印原料条码（修复变量名，用 arrivalDetails）
const handlePrintBarcode = () => {
  if (arrivalDetails.value.length === 0) {
    ElMessage.warning('暂无原料明细，无法打印');
    return;
  }
  console.log('打印原料条码数据：', arrivalDetails.value);
  ElMessage.success('正在生成打印数据...');
}

// 打印到货单
const handlePrintOrder = () => {
  console.log('打印到货单数据：', arrivalNote.value);
  ElMessage.success('正在生成到货单打印数据...');
}
</script>

<style scoped>
.arrival-detail {
  padding: 20px;
  background: #fff;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}
.detail-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}
.detail-header h2 {
  font-size: 18px;
  font-weight: bold;
  color: #333;
  margin: 0;
}
.info-form {
  display: flex;
  gap: 40px;
  margin-bottom: 20px;
  flex-wrap: wrap; /* 适配小屏幕 */
}
.material-section, .remark-section {
  margin-bottom: 20px;
}
.section-title {
  display: block;
  margin-bottom: 8px;
  font-weight: bold;
  color: #333;
}
.action-buttons {
  display: flex;
  gap: 10px;
}
/* 适配textarea高度 */
.remark-section .el-textarea__inner {
  resize: none;
}
</style>